clear variables; clear global; clear mex; close all; fclose('all'); clc
%%% NOTE: this code relies on functions from the PsychToolBox package,
%%% please make sure it is installed

dbstop if error % for debugging: trigger a debug point when an error occurs

%%%%%
% needed information about setup
scrRes  = [1920 1080]; 

%%%%%

% setup directories
myDir = fileparts(mfilename('fullpath'));
cd(myDir);
cd data;                        dirs.data       = cd;
        cd samples;             dirs.samples    = cd;   % directory where     *.tsv files with sample data generated by the readme files should be placed
cd ..;  cd msgs;                dirs.msgs       = cd;   % directory where *_msg.tsv files with messages generated by the readme files should be placed
cd ..;
if ~isdir('msgs_ophak') %#ok<*ISDIR>
    mkdir(fullfile(cd,'msgs_ophak'));
end
        cd msgs_ophak;          dirs.msgsO      = cd;
cd ..;
if ~isdir('samples_ophak')
    mkdir(fullfile(cd,'samples_ophak'));
end
        cd samples_ophak;       dirs.samplesO   = cd;
cd ..;
cd ..;  cd function_library;    dirs.funclib    = cd;
cd ..;
addpath(genpath(dirs.funclib));                 % add dirs to path

%%% cut up the data file into tasks
[files,nfiles] = FileFromFolder(dirs.samples,[],'tsv');

% check we have matching msg files
for p=nfiles:-1:1
    files(p).msgname = [files(p).fname '_msg.tsv'];
    if ~exist(fullfile(dirs.msgs,files(p).msgname),'file')
        warning('No matching message file ''%s'' found for sample file ''%s''',files(p).msgname,files(p).name)
        files(p) = [];
    end
end

if 0
    % filter so we only get data that matches the filter. uses regexp
    filtstr = '^(?!01|02|03).*$';
    results = regexpi({files.name}.',filtstr,'start');
    files   = files(~cellfun(@isempty,results));
end
nfiles = length(files);

for p=1:nfiles
    disp(files(p).name)
    % read msgs and data
    dat     = readTittaTsv(fullfile(dirs.samples,files(p).name),{'system_time_stamp','left_gaze_point_on_display_area_x','left_gaze_point_on_display_area_y','right_gaze_point_on_display_area_x','right_gaze_point_on_display_area_y','left_pupil_diameter','right_pupil_diameter'});
    ts      = dat.system_time_stamp.';
    samp    = [dat.left_gaze_point_on_display_area_x*scrRes(1) dat.left_gaze_point_on_display_area_y*scrRes(2) dat.right_gaze_point_on_display_area_x*scrRes(1) dat.right_gaze_point_on_display_area_y*scrRes(2) dat.left_pupil_diameter dat.right_pupil_diameter].';
    header  = {'t','gLX','gLY','gRX','gRY','pL','pR'};
    
    % get messages
    msgs = loadMsgsTsv(fullfile(dirs.msgs,files(p).msgname));
    [timest,what,msgs] = parseMsgs(msgs);
    
    % split up per task and write
    for q=1:length(timest.fix)
        fname = sprintf('%s_R%03d.txt',files(p).fname,q);
        fprintf('%s\n',fname);
        
        % msgs
        fid = fopen(fullfile(dirs.msgsO,fname),'wt');
        t = msgs{q}.';
        fprintf(fid,'%d\t%s\n',t{:});
        fclose(fid);
        
        % data
        fid = fopen(fullfile(dirs.samplesO,fname),'wt');
        fmt = repmat('%s\t',1,length(header));
        fmt(end) = 'n';
        % header
        fprintf(fid,fmt,header{:});
        % data
        fmt = ['%ld\t' repmat('%.2f\t',1,length(header)-3) repmat('%.4f\t',1,2)];
        fmt(end) = 'n';
        qSel = ts>=timest.fix(q) & ts<=timest.end(q);
        data = [num2cell(ts(qSel)); num2cell(samp(:,qSel))];
        fprintf(fid,fmt,data{:});
        fclose(fid);
    end
end

rmpath(genpath(dirs.funclib));                  % cleanup path
